package com.qixin.modules.dataauth.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qixin.modules.dataauth.entity.SysDataAuth;
import com.qixin.modules.dataauth.entity.SysDataAuthOrg;
import com.qixin.modules.dataauth.entity.SysUserData;
import com.qixin.modules.dataauth.service.ISysDataAuthOrgService;
import com.qixin.modules.dataauth.service.ISysDataAuthService;
import com.qixin.modules.dataauth.service.ISysUserDataService;
import com.qixin.modules.dataauth.vo.UserDataOrgVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 数据权限配置表
 * @Author: qixin-boot
 * @Date: 2021-08-18
 * @Version: V1.0
 */
@Api(tags = "数据权限配置表")
@RestController
@RequestMapping("/dataauth/sysDataAuth")
@Slf4j
public class SysDataAuthController extends JeecgController<SysDataAuth, ISysDataAuthService> {

    @Autowired
    private ISysDataAuthService sysDataAuthService;

    // 数据权限组织
    @Autowired
    private ISysDataAuthOrgService sysDataAuthOrgService;

    // 用户数据权限
    @Autowired
    private ISysUserDataService sysUserDataService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param sysDataAuth
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "数据权限配置表-分页列表查询", notes = "数据权限配置表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(SysDataAuth sysDataAuth,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SysDataAuth> queryWrapper = QueryGenerator.initQueryWrapper(sysDataAuth, req.getParameterMap());
        Page<SysDataAuth> page = new Page<SysDataAuth>(pageNo, pageSize);
        IPage<SysDataAuth> pageList = sysDataAuthService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sysDataAuth
     * @return
     */
    @AutoLog(value = "数据权限配置表-添加")
    @ApiOperation(value = "数据权限配置表-添加", notes = "数据权限配置表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysDataAuth sysDataAuth) {
        sysDataAuthService.save(sysDataAuth);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysDataAuth
     * @return
     */
    @AutoLog(value = "数据权限配置表-编辑")
    @ApiOperation(value = "数据权限配置表-编辑", notes = "数据权限配置表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysDataAuth sysDataAuth) {
        sysDataAuthService.updateById(sysDataAuth);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "数据权限配置表-通过id删除")
    @ApiOperation(value = "数据权限配置表-通过id删除", notes = "数据权限配置表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        Integer count = sysDataAuthService.countSyuser(id);
        if (count > 0) {
            throw new JeecgBootException("删除失败!已绑定用户");
        }
        sysDataAuthService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "数据权限配置表-批量删除")
    @ApiOperation(value = "数据权限配置表-批量删除", notes = "数据权限配置表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysDataAuthService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "数据权限配置表-通过id查询", notes = "数据权限配置表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SysDataAuth sysDataAuth = sysDataAuthService.getById(id);
        if (sysDataAuth == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sysDataAuth);
    }

    /**
     * description: 通过用户ID查询组织实体
     * create time: 2021/11/25 20:06
     * create by: wjb
     * @params
     * @return
     */


    /**
     * 保存授权组织
     *
     * @return
     */
    @RequestMapping(value = "/saveAuthOrg", method = RequestMethod.POST)
    //@RequiresRoles({ "admin" })
    public Result<String> saveRolePermission(@RequestBody JSONObject json) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            String dataAuthId = json.getString("dataAuthId");
            String orgId = json.getString("orgIds");
            String[] orgIds = orgId.split(",");
            QueryWrapper<SysDataAuthOrg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("data_auth_id", dataAuthId);
            sysDataAuthOrgService.remove(queryWrapper);
            List<SysDataAuthOrg> dataAuthOrgList = new ArrayList<>();
            for (String oid : orgIds) {
                SysDataAuthOrg sysDataAuthOrg = new SysDataAuthOrg();
                sysDataAuthOrg.setDataAuthId(dataAuthId);
                sysDataAuthOrg.setOrgId(oid);
                dataAuthOrgList.add(sysDataAuthOrg);
            }
            sysDataAuthOrgService.saveBatch(dataAuthOrgList);
            result.success("保存成功！");
            log.info("======角色授权成功=====耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 查询组织授权
     *
     * @return
     */
    @RequestMapping(value = "/queryAuthOrg", method = RequestMethod.GET)
    public Result<List<String>> queryRolePermission(@RequestParam(name = "dataAuthId", required = true) String dataAuthId) {
        Result<List<String>> result = new Result<>();
        try {
            QueryWrapper<SysDataAuthOrg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("data_auth_id", dataAuthId);
            List<SysDataAuthOrg> list = sysDataAuthOrgService.list(queryWrapper);
            result.setResult(list.stream().map(dataAuthOrg -> String.valueOf(dataAuthOrg.getOrgId())).collect(Collectors.toList()));
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 查询未授权用户
     *
     * @return
     */
    @RequestMapping(value = "/queryNotAuthUser", method = RequestMethod.GET)
    public Result<IPage<SysUser>> queryPageList(@RequestParam(name = "dataAuthId", required = true) String dataAuthId,
                                                @RequestParam(name = "username", required = false) String username,
                                                @RequestParam(name = "realname", required = false) String realname,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Result<IPage<SysUser>> result = new Result<IPage<SysUser>>();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>();
        queryWrapper.eq("user_type", 1);
        // 组织权限过滤
        List<String> orgIds = loginUser.getOrgAuth();
        if (orgIds != null && StrUtil.isNotBlank(loginUser.getOrgCode())) {
            orgIds.add(loginUser.getOrgCode());
        } else {
            orgIds = new ArrayList<>();
            orgIds.add(loginUser.getOrgCode());
        }

        if (StrUtil.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        if (StrUtil.isNotBlank(realname)){
            queryWrapper.like("realname",realname);
        }
        queryWrapper.in("org_code", orgIds);
        // 过滤已授权人员
        queryWrapper.notInSql("id","SELECT user_id FROM sys_user_data d WHERE d.data_auth_id = '"+ dataAuthId +"'");

        Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
        IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);

        // 设置组织
        pageList.getRecords().forEach(item -> {
            if (StrUtil.isNotBlank(item.getOrgCode())) {
                SysDepart org = sysDepartService.queryCompByOrgCode(item.getOrgCode());
                if (org != null) {
                    item.setOrgCodeTxt(org.getDepartName());
                }
            }
        });
        result.setSuccess(true);
        result.setResult(pageList);
        log.info(pageList.toString());
        return result;
    }


    /**
     * 给指定数据权限添加用户
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/addUserDataOrg", method = RequestMethod.POST)
    public Result<String> addSysUserRole(@RequestBody UserDataOrgVO userDataOrgVO) {
        Result<String> result = new Result<String>();
        try {
            String dataAuthId = userDataOrgVO.getDataAuthId();

            // 设置用户权限
            List<SysUserData> list = new ArrayList();
            for (String userid : userDataOrgVO.getUserIdList()) {
                SysUserData userData = new SysUserData();
                userData.setDataAuthId(dataAuthId);
                userData.setUserId(userid);
                list.add(userData);
            }
            sysUserDataService.saveBatch(list);
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     * 查询数据权限用户
     *
     * @param pageNo
     * @param pageSize
     * @param dataAuthId
     * @param req
     * @return
     */
    @RequestMapping(value = "/queryUserList", method = RequestMethod.GET)
    public Result<IPage<Map<String, String>>> queryUserList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            @RequestParam(name = "dataAuthId") String dataAuthId,
                                                            @RequestParam(name = "userName", required = false) String userName,
                                                            HttpServletRequest req) {
        Result<IPage<Map<String, String>>> result = new Result<IPage<Map<String, String>>>();
        Page<Map<String, String>> page = new Page<Map<String, String>>(pageNo, pageSize);
        IPage<Map<String, String>> pageList = sysDataAuthService.queryUserList(page, dataAuthId,userName);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUsers", method = RequestMethod.DELETE)
    public Result<?> deleteUserRoleBatch(
            @RequestParam(name = "dataAuthId") String dataAuthId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        Result<?> result = new Result<>();
        try {
            Object[] array;
            List userIdList = Arrays.asList(userIds.split(","));
            QueryWrapper<SysUserData> queryWrapper = new QueryWrapper<SysUserData>();
            queryWrapper.eq("data_auth_id", dataAuthId);
            queryWrapper.in("user_id", userIdList);
            sysUserDataService.remove(queryWrapper);
            // 清除缓存
            for ( Object id:userIdList) {
                SysUser sysUser = sysUserService.getById(id.toString());
                if(sysUser != null){
                    redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
                }
            }
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysDataAuth
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysDataAuth sysDataAuth) {
        return super.exportXls(request, sysDataAuth, SysDataAuth.class, "数据权限配置表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysDataAuth.class);
    }

}
